$(function () {
    /***
     * 页面初始化根据车辆id赋值
     */
    if(parent.layui.larryElem != undefined){
        var params = parent.layui.larryElem.boxParams;
        vm.getCarBasicInforByCarNo(params.carId);
    }

    layui.config({
        base: '../../statics/common/'
    }).extend({
        soulTable: 'layui/soultable/ext/soulTable.slim'
    });

    layui.use(['form', 'layedit', 'laydate', 'upload','soulTable'], function(){
        var form = layui.form,
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;
            form.on('submit(saveOrUpdate)', function () {
                vm.saveOrUpdate();
                return false;
            });
            form.verify({
                carNoVerify: function (value) {
                    if((vm.carRepairOrder.carNo =="" || vm.carRepairOrder.carNo==null) && (vm.carRepairOrder.vinNo =="" || vm.carRepairOrder.vinNo==null)){
                        return '请通过车牌号选择或者通过车架号选择车辆信息！';
                    }
                },
                vinNoVerify: function (value) {
                    if((vm.carRepairOrder.carNo =="" || vm.carRepairOrder.carNo==null) && (vm.carRepairOrder.vinNo =="" || vm.carRepairOrder.vinNo==null)){
                        return '请通过车牌号选择或者通过车架号选择车辆信息！';
                    }
                },
                /*  repairStartDateVerify: function (value) {
                    if (value == "" || value == null) {
                        return '维修开始时间不能为空';
                    }
                },
                faultDescVerify: function (value) {
                    if (value == "" || value == null) {
                        return '故障描述不能为空';
                    }

                },*/
                repairShopQuotationVerify: function (value) {
                    var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                /*repairContentVerify: function (value) {
                    if (value == "" || value == null) {
                        return '维修内容不能为空';
                    }
                },*/
                userPayVerify: function (value) {
                    var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
                    /*if (value == "" || value == null) {
                        return '维修价格用户支付金额不能为空';
                    }*/
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                platformPayVerify: function (value) {
                    var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                insurancePayVerify: function (value) {
                    var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                // repairEndDateVerify: function (value) {
                //     if (value == "" || value == null) {
                //         return '维修结束时间不能为空';
                //     }
                // },
                /* isSpareCarVerify: function (value) {
                     if (value == "" || value == null) {
                         return '是否提供备用车不能为空';
                     }
                 },
                 spareCarNoVerify: function (value) {
                     if (value == "" || value == null) {
                         return '备用车车牌号不能为空';
                     }
                 }*/

            });
            form.render();
    });
    //是否提供备用车
    layui.form.on('select(isSpareCar)', function (data) {
        vm.carRepairOrder.isSpareCar = data.value;
    });
    layui.form.on('select(costSettlement)', function (data) {
        vm.carRepairOrder.costSettlement = data.value;
    });
    //维修开始时间
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        //维修开始时间
        laydate.render({
            elem: '#repairStartDate',
            trigger: 'click',
            done: function (value, date, endDate) {
                vm.carRepairOrder.repairStartDate=value;
            }
        });

        //维修结束时间
        laydate.render({
            elem: '#repairEndDate',
            trigger: 'click',
            done: function (value, date, endDate) {
                vm.carRepairOrder.repairEndDate=value;
            }
        });
    });

    // //维修厂报价
    // $("#repairShopQuotation").blur(function(){
    //     var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
    //     if((vm.carRepairOrder.repairShopQuotation!=undefined) && (vm.carRepairOrder.repairShopQuotation !="") && (!reg.test(vm.carRepairOrder.repairShopQuotation))){
    //         alert("金额输入有误请重新输入");
    //         vm.carRepairOrder.repairShopQuotation="";
    //     }
    // });
    //
    // //金额输入后进行计算
    // $("#userPayId").blur(function(){
    //     var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
    //     if(reg.test(vm.carRepairOrder.userPay)){
    //         amountAccumulation();
    //     }else if((vm.carRepairOrder.userPay!=undefined) && (vm.carRepairOrder.userPay !="") && (!reg.test(vm.carRepairOrder.userPay))){
    //         alert("金额输入有误请重新输入");
    //         vm.carRepairOrder.userPay="";
    //     }else if(vm.carRepairOrder.userPay==""){
    //         amountAccumulation();
    //     }
    //
    // });
    // $("#platformPayId").blur(function(){
    //     var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
    //     if(reg.test(vm.carRepairOrder.platformPay)){
    //         amountAccumulation();
    //     }else if((vm.carRepairOrder.platformPay!=undefined) && (vm.carRepairOrder.platformPay !="") && (!reg.test(vm.carRepairOrder.platformPay))){
    //         alert("金额输入有误请重新输入");
    //         vm.carRepairOrder.platformPay="";
    //     }else if(vm.carRepairOrder.platformPay==""){
    //         amountAccumulation();
    //     }
    // });
    //
    // $("#insurancePayId").blur(function(){
    //     var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
    //     if(reg.test(vm.carRepairOrder.insurancePay)){
    //         amountAccumulation();
    //     }else if((vm.carRepairOrder.insurancePay!=undefined) && (vm.carRepairOrder.insurancePay!="") && (!reg.test(vm.carRepairOrder.insurancePay))){
    //         alert("金额输入有误请重新输入");
    //         vm.carRepairOrder.insurancePay="";
    //     }else if(vm.carRepairOrder.insurancePay==""){
    //         amountAccumulation();
    //     }
    // });

    //附件上传
    layui.upload.render({
        elem: '#addFile',
        url: baseURL + 'file/uploadInsuranceFile',
        data: {'path':'carrepairorder'},
        field:'files',
        auto:true,
        size: 50*1024*1024,
        accept: 'file', //普通文件
        acceptMime: '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg,.zip,.rar',
        exts: 'pdf|doc|docx|xls|xlsx|jpg|png|jpeg|zip|rar', //
        multiple: true,
        number:20,
        done: function (res) {
            RemoveLoading();
            if (res.code != '0') {
                layer.msg('上传失败', {icon: 5});
                vm.delFile(fileIdTmp);
                fileIdTmp = null;
                return false;
            }
            res.data.forEach(function (value) {
                var extIndex = value.resultFilePath.lastIndexOf('.');
                var ext = value.resultFilePath.slice(extIndex);
                var fileNameNotext = value.fileName;
                var regExt = /png|jpg|jpeg/;
                var fileType = regExt.test(ext) ? 1 : 0;
                fileIdTmp = vm.fileLst.length + '_' + uuid(60);
                var fileTmp = {
                    id: fileIdTmp,
                    operationId:sessionStorage.getItem("userId"),
                    operationName:sessionStorage.getItem("username"),
                    nameDesc: '维修附件',
                    nameAccessory: fileNameNotext,
                    nameFile: fileNameNotext,
                    nameExt: ext,
                    typeFile: fileType,
                    url: value.resultFilePath
                };
                vm.fileLst.push(fileTmp);
                vm.fileLstId = 'fileLstId_' + uuid(6);
            });
            fileIdTmp = null;
        },
        error: function () {
            RemoveLoading();
            layer.msg('上传失败', {icon: 5});
            vm.delFile(fileIdTmp);
            fileIdTmp = null;
        }
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        //车辆信息数据源
        carInforData:{},
        //维修单保存信息数据源
        carRepairOrder:{},
        fileLst: [],
        fileLstId: '0',
        bpmChartDtoList:[],
        openFlow:false
    },
    watch: {
        'carRepairOrder.repairShopQuotation':function(){
            var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
            if((vm.carRepairOrder.repairShopQuotation!=undefined) && (vm.carRepairOrder.repairShopQuotation !="") && (!reg.test(parseFloat(vm.carRepairOrder.repairShopQuotation)))){
                alert("金额输入有误请重新输入");
                vm.carRepairOrder.repairShopQuotation="";
                amountAccumulation();
            }
        },
        'carRepairOrder.userPay':function(){
            var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
             
            if(reg.test(parseFloat(vm.carRepairOrder.userPay))){
                amountAccumulation();
            }else if((vm.carRepairOrder.userPay!=undefined) && (vm.carRepairOrder.userPay !="") && (!reg.test(vm.carRepairOrder.userPay))){
                alert("金额输入有误请重新输入");
                vm.carRepairOrder.userPay="";
                amountAccumulation();
            }else if(vm.carRepairOrder.userPay==""){
                amountAccumulation();
            }
        },
        'carRepairOrder.platformPay':function(){
            var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
             
            if(reg.test(parseFloat(vm.carRepairOrder.platformPay))){
                amountAccumulation();
            }else if((vm.carRepairOrder.platformPay!=undefined) && (vm.carRepairOrder.platformPay !="") && (!reg.test(vm.carRepairOrder.platformPay))){
                alert("金额输入有误请重新输入");
                vm.carRepairOrder.platformPay="";
                amountAccumulation();
            }else if(vm.carRepairOrder.platformPay==""){
                amountAccumulation();
            }
        },
        'carRepairOrder.insurancePay':function(){
            var reg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
             
            if(reg.test(parseFloat(vm.carRepairOrder.insurancePay))){
                amountAccumulation();
            }else if((vm.carRepairOrder.insurancePay!=undefined) && (vm.carRepairOrder.insurancePay!="") && (!reg.test(vm.carRepairOrder.insurancePay))){
                alert("金额输入有误请重新输入");
                vm.carRepairOrder.insurancePay="";
                amountAccumulation();
            }else if(vm.carRepairOrder.insurancePay==""){
                amountAccumulation();
            }
        }
    },
    created: function () {
        var _this = this;
        $.ajaxSettings.async = false;
        $.get(baseURL + "activity/bpmInitChart",{processKey:"carRepairApprove"}, function (r) {
            if (r.code == 0){
                _this.bpmChartDtoList = r.bpmInitChart;
                _this.openFlow = r.openFlow;
            }
        });
        $.ajaxSettings.async = true;
    },
    updated: function () {
        layui.form.render();
    },
    methods: {
        //选择车牌号
        selectCarNo:function(){
            var index = layer.open({
                title: "选择车牌号",
                type: 2,
                content: tabBaseURL + "modules/common/selectcar.html",
                success: function (layero, num) {
                    var iframe = window['layui-layer-iframe' + num];
                    iframe.vm.initType('carrepairorder');
                },
                end: function(){
                    var carId=vm.carInforData.carId;
                    if(carId!=null && carId!='' && carId!=undefined){
                        vm.getCarBasicInforByCarNo(carId);
                    }
                }
            });
            layer.full(index);

        },
        //选择车架号
        selectVinNo:function(){
            var index = layer.open({
                title: "选择车架号",
                type: 2,
                content: tabBaseURL + "modules/common/selectcar.html",
                success: function (layero, num) {
                    var iframe = window['layui-layer-iframe' + num];
                    iframe.vm.initType('carrepairorder');
                },
                end: function(){
                    var vinNo=vm.carInforData.vinNo;
                    if(vinNo!=null && vinNo!=''&& vinNo!=undefined){
                        vm.getCarBasicInforByVinNo(vinNo);
                    }
                }
            });
            layer.full(index);

        },
        //根据车牌号查询基本信息
        getCarBasicInforByCarNo:function (carId) {
            $.ajax({
                type: "POST",
                url: baseURL + "car/tcarbasic/getCarBasicInforByCarNo/"+carId,
                contentType: "application/json",
                data: {},
                success: function(r){
                    vm.carRepairOrder=r.baseInfor;
                }
            });
        },
        //根据车架号查询基本信息
        getCarBasicInforByVinNo:function (vinNo) {
            $.ajax({
                type: "POST",
                url: baseURL + "car/tcarbasic/getCarBasicInforByVinNo/"+vinNo,
                contentType: "application/json",
                data: {},
                success: function(r){
                    if(r.baseInfor!=null){
                        vm.carRepairOrder=r.baseInfor;
                    }else {
                        alert("该车架号暂无车辆信息!");
                        return;
                    }
                }
            });
        },
        //取消
        cancel: function(){
            // parent.layer.closeAll();
            //页面关闭
            closeCurrent();
        },
        //保存修改方法
        saveOrUpdate: function (event) {
            vm.carRepairOrder.carPlateNo=vm.carRepairOrder.carNo;
            vm.carRepairOrder.orderNo=vm.carRepairOrder.carOrderNo;
            vm.carRepairOrder.carPurpose=vm.carRepairOrder.rentType;
            vm.carRepairOrder.factoryId=vm.carRepairOrder.depotId;
            vm.carRepairOrder.factoryName=vm.carRepairOrder.deptName;
            vm.carRepairOrder.fileLst = vm.fileLst;
            vm.carRepairOrder.customer = vm.carRepairOrder.customerName;
            vm.carRepairOrder.depotId= vm.carRepairOrder.carDepotId;
            vm.carRepairOrder.depotName= vm.carRepairOrder.carDepotName;
            var url ="carrepairorder/carrepairorder/save";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.carRepairOrder),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            /*parent.layer.closeAll();
                            parent.vm.reload();*/
                            //页面关闭
                            closeCurrent();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        delFile: function (id) {
            for(var i = 0 ;i<vm.fileLst.length;i++) {
                if(vm.fileLst[i].id === id) {
                    vm.fileLst.splice(i,1);
                    i= i-1;
                }
            }
        },
    }
})

function initUpload(upload) {
    var operationId = sessionStorage.getItem("userId");
    var operationName = sessionStorage.getItem("username");
    upload.render({
        elem: '#addFile',
        url: baseURL + 'file/uploadFile',
        data: {'path':'contract'},
        field:'files',
        auto:true,
        size: 50*1024*1024,
        accept: 'file', //普通文件
        acceptMime: '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg',
        exts: 'pdf|doc|docx|xls|xlsx|jpg|png|jpeg', //
        multiple: true,
        number:20,
        choose: function(obj){
            PageLoading();
            obj.preview(function(index, file, result){
                var fileName = file.name;
                var extIndex = fileName.lastIndexOf('.');
                var ext = fileName.slice(extIndex);
                var fileNameNotext = fileName.slice(0, extIndex);
                var regExt = /png|jpg|jpeg/;
                var fileType = regExt.test(ext) ? 1:0;
                fileIdTmp = vm.fileLst.length + '_' + uuid(60);
                var fileTmp={
                    id: fileIdTmp,
                    operationId:operationId,
                    operationName:operationName,
                    nameDesc:'维修附件',
                    nameAccessory:fileNameNotext,
                    nameFile:fileName,
                    nameExt:ext,
                    typeFile:fileType,
                };
                vm.fileLst.push(fileTmp);
            });
        },
        done: function (res) {
            RemoveLoading();
            if (res.code == '0') {
                vm.fileLst.forEach(function (value) {
                    if (value.id === fileIdTmp) value.url = res.data[0];
                });
                vm.fileLstId = 'fileLstId_' + uuid(6);
            } else {
                layer.msg('上传失败', {icon: 5});
                vm.delFile(fileIdTmp);
            }
            fileIdTmp = null;
        },
        error: function () {
            RemoveLoading();
            layer.msg('上传失败', {icon: 5});
            vm.delFile(fileIdTmp);
            fileIdTmp = null;
        }
    });
}

function amountAccumulation(){
    $.ajax({
        type: "POST",
        url: baseURL + 'carrepairorder/carrepairorder/amountAccumulation',
        contentType: "application/json",
        data:JSON.stringify(vm.carRepairOrder),
        success: function(r){
            vm.carRepairOrder = Object.assign({}, vm.carRepairOrder, {totalPay: r.amountAccumulation});
        }
    });

}


